package com.eastdigit.shiro.authc;

import java.util.concurrent.atomic.AtomicInteger;

import net.sf.json.JSONObject;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import com.eastdigit.system.service.SpringServiceFactory;
import com.gjzt.business.media.service.WuhanbusAPIService;

/**
 * <p>
 * User: Zhang Kaitao
 * <p>
 * Date: 14-1-28
 * <p>
 * Version: 1.0
 */
public class RetryLimitHashedCredentialsMatcher extends SimpleCredentialsMatcher {

    private Cache<String, AtomicInteger> passwordRetryCache;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String userId = String.valueOf(token.getPrincipal());
        // retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(userId);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(userId, retryCount);
        }
        if (retryCount.incrementAndGet() > 5) {
            // if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }
        
        boolean matches = false;
        
        if((token instanceof StateToken) && ((StateToken)token).isWhBusUserLogin()){
        	WuhanbusAPIService service = (WuhanbusAPIService)SpringServiceFactory.getInstance("wuhanbusAPIService", WuhanbusAPIService.class);
        	JSONObject result = service.login(((StateToken)token).getUsername(), String.valueOf(((StateToken)token).getPassword()));
        	if(result != null && result.containsKey("errcode") && "0".equals(String.valueOf(result.get("errcode")))){
        		matches = true;
        	}
        }else{
        	matches = super.doCredentialsMatch(token, info);
        }
        if (matches) {
            // clear retry count
            passwordRetryCache.remove(userId);
        }
        return matches;
    }
}
